<?php
require 'pingpp/init.php';
// ping++支付库
class Pingpplib
{
    // api_key 获取方式：登录 [Dashboard](https://dashboard.pingxx.com)->点击管理平台右上角公司名称->企业设置->开发设置->Live/Test Secret Key
    // app_id 获取方式：登录 [Dashboard](https://dashboard.pingxx.com)->应用卡片下方
    var $conf = array(
        'APP_KEY' => 'sk_live_u58WjT5eT0yPrjjrTCSqbjbP', // 'sk_test_5qjvX9KmLeL0TC0y1KSiD0eT',//测试APP_KEY
        'APP_ID' => 'app_qrzrLGfbTOuHbLO4'
    );
    
    // P++支付，默认微信支付
    // amount以分为单位
    function ini_wechat($order_no, $subject, $body, $amount, $open_id, $channel = 'wx_pub')
    {
        \Pingpp\Pingpp::setApiKey($this->conf['APP_KEY']); // 设置 API Key
        
        \Pingpp\Pingpp::setPrivateKeyPath(__DIR__ . '/pingpp/key/your_rsa_private_key.pem'); // 设置私钥
                                                                                             
        // 用户openid
        $extra = array(
            'open_id' => $open_id
        ) // 用户在商户微信公众号下的唯一标识，获取方式可参考 pingpp-php/lib/WxpubOAuth.php
;
        
        try {
            $ch = \Pingpp\Charge::create(array(
                // 请求参数字段规则，请参考 API 文档：https://www.pingxx.com/api#api-c-new
                'subject' => $subject,
                'body' => $body,
                'amount' => $amount, // 订单总金额, 人民币单位：分（如订单总金额为 1 元，此处请填 100）
                'order_no' => $order_no, // 推荐使用 8-20 位，要求数字或字母，不允许其他字符
                'currency' => 'cny',
                'extra' => $extra,
                'channel' => $channel, // 支付使用的第三方支付渠道取值，请参考：https://www.pingxx.com/api#api-c-new
                'client_ip' => $_SERVER['REMOTE_ADDR'], // 发起支付请求客户端的 IP 地址，格式为 IPV4，如: 127.0.0.1
                'app' => array(
                    'id' => $this->conf['APP_ID']
                )
            ));
            
            return $ch;
        } catch (\Pingpp\Error\Base $e) {
            // 捕获报错信息
            if ($e->getHttpStatus() != null) {
                return $e->getHttpBody();
            } else {
                return $e->getMessage();
            }
        }
    }
    
    // 支付完成
    function after_pay()
    {
        /*
         * 验证 webhooks 签名方法：
         * raw_data：Ping++ 请求 body 的原始数据即 event ，不能格式化；
         * signature：Ping++ 请求 header 中的 x-pingplusplus-signature 对应的 value 值；
         * pub_key_path：读取你保存的 Ping++ 公钥的路径；
         * pub_key_contents：Ping++ 公钥，获取路径：登录 [Dashboard](https://dashboard.pingxx.com)->点击管理平台右上角公司名称->开发信息-> Ping++ 公钥
         */
        // $raw_data = '{"id":"evt_eYa58Wd44Glerl8AgfYfd1sL","created":1434368075,"livemode":true,"type":"charge.succeeded","data":{"object":{"id":"ch_bq9IHKnn6GnLzsS0swOujr4x","object":"charge","created":1434368069,"livemode":true,"paid":true,"refunded":false,"app":"app_vcPcqDeS88ixrPlu","channel":"wx","order_no":"2015d019f7cf6c0d","client_ip":"140.227.22.72","amount":100,"amount_settle":0,"currency":"cny","subject":"An Apple","body":"A Big Red Apple","extra":{},"time_paid":1434368074,"time_expire":1434455469,"time_settle":null,"transaction_no":"1014400031201506150354653857","refunds":{"object":"list","url":"/v1/charges/ch_bq9IHKnn6GnLzsS0swOujr4x/refunds","has_more":false,"data":[]},"amount_refunded":0,"failure_code":null,"failure_msg":null,"metadata":{},"credential":{},"description":null}},"object":"event","pending_webhooks":0,"request":"iar_Xc2SGjrbdmT0eeKWeCsvLhbL"}';
        $raw_data = file_get_contents('php://input');
        $headers = \Pingpp\Util\Util::getRequestHeaders();
        // 签名在头部信息的 x-pingplusplus-signature 字段
        $signature = isset($headers['X-Pingplusplus-Signature']) ? $headers['X-Pingplusplus-Signature'] : NULL;
        // 示例
        // $signature = 'BX5sToHUzPSJvAfXqhtJicsuPjt3yvq804PguzLnMruCSvZ4C7xYS4trdg1blJPh26eeK/P2QfCCHpWKedsRS3bPKkjAvugnMKs+3Zs1k+PshAiZsET4sWPGNnf1E89Kh7/2XMa1mgbXtHt7zPNC4kamTqUL/QmEVI8LJNq7C9P3LR03kK2szJDhPzkWPgRyY2YpD2eq1aCJm0bkX9mBWTZdSYFhKt3vuM1Qjp5PWXk0tN5h9dNFqpisihK7XboB81poER2SmnZ8PIslzWu2iULM7VWxmEDA70JKBJFweqLCFBHRszA8Nt3AXF0z5qe61oH1oSUmtPwNhdQQ2G5X3g==';
        
        // Ping++ 公钥，获取路径：登录 [Dashboard](https://dashboard.pingxx.com)->点击管理平台右上角公司名称->开发信息-> Ping++ 公钥
        $pub_key_path = __DIR__ . "/pingpp/key/pingpp_rsa_public_key.pem";
        
        $result = $this->_verify_signature($raw_data, $signature, $pub_key_path);
        
        $result = $this->_verify_signature($raw_data, $signature, $pub_key_path);
        
        if ($result === 1) {
            // 验证通过
            return $raw_data;
        } elseif ($result === 0) {
            return false;
        } else {
            return false;
        }
    }

    private function _verify_signature($raw_data, $signature, $pub_key_path)
    {
        $pub_key_contents = file_get_contents($pub_key_path);
        // php 5.4.8 以上，第四个参数可用常量 OPENSSL_ALGO_SHA256
        return openssl_verify($raw_data, base64_decode($signature), $pub_key_contents, 'sha256');
    }
}

?>